package main

import (
	"bufio"

	"fb/sort/algorithms/base"
	"fb/sort/algorithms/bubblesort"
	"fb/sort/algorithms/heap"
	"fb/sort/algorithms/partition"
	"fb/sort/algorithms/qsort"

	"flag"
	"fmt"
	"os"
	"strconv"
)

var infile = flag.String("i", "infile", "输入文件路径")
var outfile = flag.String("o", "outfile", "文件输出路径")
var algorithm = flag.String("a", "algorithm", "算法排序 qsort(快速排序) , bubblesort（冒泡排序） , heap（堆排序） , base（基数排序），partition(归并排序)")

func main() {
	flag.Parse()
	if *infile != "infile" && *outfile != "outfile" && *algorithm != "algorithm" {
		v, err := readFileInt(*infile)
		if err != nil {
			fmt.Println("请检查文件")
			return
		}

		fmt.Println("排序前")
		fmt.Println(v)

		switch *algorithm {
		case "qsort":
			qsort.Sort(v)
		case "bubblesort":
			bubblesort.Sort(v)
		case "heap":
			heap.Sort(v)
		case "base":
			base.Sort(v)
		case "partition":
			partition.Sort(v)
		default:
			fmt.Println("没有匹配到该算法")
			return
		}

		fmt.Println("排序后：")
		fmt.Println(v)

		err = writeFileInts(*outfile, v)

		if err != nil {
			fmt.Println("请检查文件输出路径")
		}

	} else {
		fmt.Println("请输入正确的指令")
	}
}

func readFileInt(infile string) (v []int, err error) {
	file, err := os.Open(infile)
	if err != nil {
		fmt.Println("Unable to open " + infile)
	}

	defer file.Close()

	br := bufio.NewReader(file)

	v = make([]int, 0)

	for {
		line, isPrefix, err := br.ReadLine()

		if err != nil {
			break
		}

		if isPrefix {
			fmt.Println("A too long line, seems unexpected.")
		}

		str := string(line)

		number0, err := strconv.Atoi(str)

		v = append(v, number0)
	}

	return v, err
}

func writeFileInts(filePath string, v []int) error {
	fout, err := os.Create(filePath)
	defer fout.Close()

	if err != nil {
		fmt.Println(filePath, err)
		return err
	}

	for _, num := range v {
		fout.WriteString(strconv.Itoa(num))
		fout.WriteString("\n")
	}

	return err
}
